package com.yzs.exam.config.spring.vx;

import com.yzs.exam.common.base.SystemCode;
import com.yzs.exam.config.spring.security.RestUtil;
import com.yzs.exam.context.WxContext;
import com.yzs.exam.entity.User;
import com.yzs.exam.entity.UserToken;
import com.yzs.exam.service.UserService;
import com.yzs.exam.service.UserTokenService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 自定义拦截器 -- 使用的springaop原理 -- prehandler -- 请求前处理 -- controller执行前
 * @author yzs
 * @create 2021-03-23 16:37
 */
@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(TokenHandlerInterceptor.class);
    private final UserTokenService userTokenService;
    private final UserService userService;
    private final WxContext wxContext;

    @Autowired
    public TokenHandlerInterceptor(UserTokenService userTokenService, UserService userService, WxContext wxContext) {
        this.userTokenService = userTokenService;
        this.userService = userService;
        this.wxContext = wxContext;
    }

    /**
     * 用户登录处理、权限检查
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        //token为空 -- 用户未登录
        if (StringUtils.isEmpty(token)) {
            logger.info("token为空");
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        if (StringUtils.isBlank(token)) {
            logger.info("token为空格");
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        if (token.length() != 36) {
            logger.info("token长度不足36");
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        UserToken userToken = userTokenService.getToken(token);
        if (null == userToken) {
            logger.info("token所对应的usertoken为空");
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        Date now = new Date();
        User user = userService.getUserByUserName(userToken.getUserName());
        if (now.before(userToken.getEndTime())) { //令牌未过期
            logger.info("令牌过期");
            wxContext.setContext(user,userToken);
            return true;
        } else {   //refresh token
            logger.info("更新令牌");
            UserToken refreshToken = userTokenService.insertUserToken(user);
            RestUtil.response(response, SystemCode.AccessTokenError.getCode(), SystemCode.AccessTokenError.getMessage(), refreshToken.getToken());
            return false;
        }
    }
}
